'use strict';

const BaseService = require('../base');
const { Op } = require('sequelize');

class ProductSkuService extends BaseService {
  static get modelName() {
    return 'Business.ProductSku';
  }

  getDetailInclude() {
    return [
      {
        model: this.ctx.model.Business.Product,
        as: 'product'
      }
    ]
  }
  async beforeCreate(data) {
    if (!data.product_id || !data.spec_combination) {
      throw new Error('商品ID和规格组合不能为空');
    }
    // spec_combination："{\"规格\":\"半只\",\"包装\":\"真空包装\",\"颜色\":\"深空黑色\",\"存储\":\"128GB\"}"
    // spec_combination："{\"颜色\":\"深空黑色\",\"规格\":\"半只\",\"存储\":\"128GB\",\"包装\":\"真空包装\"}"
    // 需要将spec_combination转换为对象，并按照规格名称排序，然后转换为JSON字符串
    const specCombination = JSON.parse(data.spec_combination);
    const sortedSpecCombination = Object.keys(specCombination).sort().reduce((obj, key) => {
      obj[key] = specCombination[key];
      return obj;
    }, {});
    data.spec_combination = JSON.stringify(sortedSpecCombination);
    console.log(data.spec_combination,'data.spec_combination')
    const res = await this.model.findOne({
      where: {
        spec_combination: data.spec_combination,
        product_id: data.product_id
      }
    })
    if (res) {
      throw new Error('规格不能重复');
    }
    return data
  }

  async beforeUpdate(id, data) {
    if (!data.spec_combination) {
      throw new Error('规格组合不能为空');
    }
    const specCombination = JSON.parse(data.spec_combination);
    const sortedSpecCombination = Object.keys(specCombination).sort().reduce((obj, key) => {
      obj[key] = specCombination[key];
      return obj;
    }, {});
    data.spec_combination = JSON.stringify(sortedSpecCombination);
    console.log(data.spec_combination,'data.spec_combination')
    const res = await this.model.findOne({
      where: {
        product_id: data.product_id,
        spec_combination: data.spec_combination,
        id: {
          [Op.ne]: id
        }
      }
    })
    if (res) {
      throw new Error('规格不能重复');
    }
    return data
  }

  /**
   * 生成SKU组合
   * @param {number} product_id 商品ID
   * @returns {Object} 生成结果
   */
  async generateSkuCombinations(product_id) {
    const { ctx } = this;

    // 1. 获取商品的所有规格
    const specs = await ctx.model.Business.ProductSpec.findAll({
      where: {
        product_id,
        status: 1
      },
      order: [['sort', 'ASC']],
      raw: true
    });

    if (specs.length === 0) {
      throw new Error('该商品没有配置规格');
    }

    // 2. 解析规格值
    const specConfigs = specs.map(spec => ({
      spec_name: spec.spec_name,
      spec_values: JSON.parse(spec.spec_values || '[]')
    })).filter(spec => spec.spec_values.length > 0);

    if (specConfigs.length === 0) {
      throw new Error('规格值不能为空');
    }

    // 3. 生成所有规格组合
    const combinations = this.generateCombinations(specConfigs);

    // 4. 检查已存在的SKU
    const existingSkus = await this.model.findAll({
      where: { product_id }
    });

    const existingCombinations = new Set();
    existingSkus.forEach(sku => {
      if (sku.spec_combination) {
        // 需要将spec_combination转换为对象，并按照规格名称排序，然后转换为JSON字符串
        const specCombination = JSON.parse(sku.spec_combination);
        const sortedSpecCombination = Object.keys(specCombination).sort().reduce((obj, key) => {
          obj[key] = specCombination[key];
          return obj;
        }, {});
        sku.spec_combination = JSON.stringify(sortedSpecCombination);
        existingCombinations.add(sku.spec_combination);
      }
    });

    // 5. 过滤出新的组合
    const newCombinations = combinations.filter(combination => {
      const specCombination = JSON.stringify(combination.spec_combination);
      return !existingCombinations.has(specCombination);
    });
    // 6. 生成SKU数据
    const skuDataList = newCombinations.map(combination => {
      const specCombination = combination.spec_combination
      const sortedSpecCombination = Object.keys(specCombination).sort().reduce((obj, key) => {
        obj[key] = specCombination[key];
        return obj;
      }, {});
      return {
        product_id,
        sku_code: this.generateSkuCode(product_id, combination.spec_combination),
        spec_combination: JSON.stringify(sortedSpecCombination),
        price: 0.00,
        original_price: 0.00,
        stock: 0,
        unit: '个',
        status: 1
      }
    });

    // 7. 批量创建SKU
    let createdCount = 0;
    if (skuDataList.length > 0) {
      const createdSkus = await this.model.bulkCreate(skuDataList);
      createdCount = createdSkus.length;
    }

    return {
      totalCombinations: combinations.length,
      existingCount: existingSkus.length,
      newCount: newCombinations.length,
      createdCount,
      combinations: newCombinations,
      message: `成功生成 ${createdCount} 个新SKU组合，总共 ${combinations.length} 个组合`
    };
  }

  /**
   * 检查SKU是否存在
   * @param {number} product_id 商品ID
   * @param {string} spec_combination 规格组合JSON字符串
   * @returns {boolean} 是否存在
   */
  async checkSkuExists(product_id, spec_combination) {
    const { ctx } = this;

    // 验证JSON格式
    let parsedCombination;
    try {
      parsedCombination = JSON.parse(spec_combination);
    } catch (error) {
      throw new Error('规格组合JSON格式不正确');
    }

    const existingSku = await this.findOne({
      where: {
        product_id,
        spec_combination
      }
    });

    return !!existingSku;
  }

  /**
   * 批量创建SKU
   * @param {Array} skuList SKU列表
   * @returns {Object} 创建结果
   */
  async batchCreate(skuList) {
    const { ctx } = this;

    const results = {
      success: [],
      failed: [],
      total: skuList.length
    };

    for (const skuData of skuList) {
      try {
        // 检查必填字段
        if (!skuData.product_id || !skuData.spec_combination) {
          results.failed.push({
            data: skuData,
            error: '商品ID和规格组合不能为空'
          });
          continue;
        }

        // 验证规格组合JSON格式
        try {
          JSON.parse(skuData.spec_combination);
        } catch (error) {
          results.failed.push({
            data: skuData,
            error: '规格组合JSON格式不正确'
          });
          continue;
        }

        // 检查是否已存在
        const exists = await this.checkSkuExists(skuData.product_id, skuData.spec_combination);
        if (exists) {
          results.failed.push({
            data: skuData,
            error: 'SKU已存在'
          });
          continue;
        }

        // 生成SKU编码
        if (!skuData.sku_code) {
          const specCombination = JSON.parse(skuData.spec_combination);
          skuData.sku_code = this.generateSkuCode(skuData.product_id, specCombination);
        }

        // 创建SKU
        const createdSku = await this.create(skuData);
        results.success.push(createdSku);

      } catch (error) {
        results.failed.push({
          data: skuData,
          error: error.message
        });
      }
    }

    return {
      ...results,
      successCount: results.success.length,
      failedCount: results.failed.length
    };
  }

  /**
   * 生成规格组合
   * @param {Array} specConfigs 规格配置数组
   * @returns {Array} 所有可能的组合
   */
  generateCombinations(specConfigs) {
    const result = [];

    const generate = (current, index) => {
      if (index === specConfigs.length) {
        const specCombination = {};
        specConfigs.forEach((spec, i) => {
          specCombination[spec.spec_name] = current[i];
        });
        result.push({ spec_combination: specCombination });
        return;
      }

      for (const value of specConfigs[index].spec_values) {
        current[index] = value;
        generate(current, index + 1);
      }
    };

    generate(new Array(specConfigs.length), 0);
    return result;
  }

  /**
   * 生成SKU编码
   * @param {number} product_id 商品ID
   * @param {Object} specCombination 规格组合对象
   * @returns {string} SKU编码
   */
  generateSkuCode(product_id, specCombination) {
    console.log('specCombination',specCombination)
    const values = Object.values(specCombination);
    return `${product_id}_${values.join('_')}`;
  }
}

module.exports = ProductSkuService;
